package Score

import (
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/controllers/login"
	"OnlineRetailers/models/Admin"
	USER "OnlineRetailers/models/User"
	"OnlineRetailers/models/User/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type GetScoreMess struct {
	beego.Controller
}

func (c *GetScoreMess) GetScoreMess() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Score/GetScoreMess"
	res := resMes.GetScoreMess{}
	coupons := []*Admin.Coupon{}
	address := &USER.Address{}
	user := &USER.WXUser{}
	log := &error2.Log{}
	var err error
	o := orm.NewOrm()

	fmt.Println(c.Ctx.Request.Header)

	err, openid := login.CheckOpenid(c.Ctx.Request.Header["Openid"])
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	user.OpenId = openid
	err = o.Read(user)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	if user.Address.AddressId != "0" {
		sql := "select * from `address` where address_id=?"
		_ = o.Raw(sql, user.Address.AddressId).QueryRow(&address)
		if !address.Default {
			address = &USER.Address{}
		}
	}

	sql := "select * from `coupon` left join `w_x_user_coupons` on `w_x_user_coupons`.`coupon_id`=`coupon`.`coupon_id` where `w_x_user_coupons`.`w_x_user_id`=? and `used`=0"
	_, err = o.Raw(sql, user.OpenId).QueryRows(&coupons)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	res.Address = address
	res.Coupon = coupons
	res.Code = "200"
	c.Data["json"] = res

}
